<?php

namespace IDock\Insurance\TPIC\Response;

use IDock\Http\Response;
use IDock\IDock\IDockEnums;
use IDock\Insurance\TPIC\Response\AllTPICResponse;
use IDock\Insurance\TPIC\TPICEnums;
use IDock\Printer\NonCar\NonCarInquiryPrinter;
use IDock\Printer\NonCar\NonCarInquirySinglePrinter;
use IDock\Printer\Premium\PremiumBIPrinter;
use IDock\Printer\Premium\PremiumCIPrinter;
use IDock\Printer\Premium\PremiumCoveragePrinter;
use IDock\Printer\Premium\PremiumFactorPrinter;
use IDock\Printer\Premium\PremiumInquiryPrinter;
use IDock\Printer\Premium\PremiumTaxPrinter;
use IDock\Printer\VehicleModelPrinter;
use IDock\Printer\VehiclePrinter;
use IDock\Visitor\NonCar\NonCarProductVisitor;

class OfferOrderPriceResponse extends AllTPICResponse
{
    public $printer = PremiumInquiryPrinter::class;
    public function resolve(): Response
    {
        $body = $this->getBody();
        if ($this->printer) {
            $this->printer = new $this->printer;
        }
        if ($body) {
            $xml = simplexml_load_string($body);
            $body = $this->objectToArray($xml);
            $status = $body['head']['status'] ?? '';
            $message = $body['head']['errMsg'] ?? '';
            $this->setBody($body);
            if ($status != 'S' && strpos($message, '重复投保') === false) {
                $this->setError(($status ?: '') . ":" . $message);
                return $this;
            }
        }

        return $this;
    }

    public function printerInit(): Response
    {
        $premiumInquiryPrinter = $this->printer;
        $modelList = [];
        $body = $this->getBody()['body'] ?? '';
        $msg = $this->getBody()['head']['errMsg'] ?? '';

        $this->getRepeatData($msg);

        if ($this->printer->repeatInsuredFlg) {
            $this->printer->success = false;
            $this->printer->repeatMessage = $msg;
            return $this;
        }
        $status = $this->getBody()['head']['status'] ?? '';
        if ($status != 'S') {
            $premiumInquiryPrinter->success = false;
            $this->printer = $premiumInquiryPrinter;
            $this->setError( $msg);
            return $this;
        }
        $jqPremium = $syPremium = 0;
        if (isset($body['itemKindBZ'])) {
            $jqPremium = $body['itemKindBZ']['priceTaxTotal'] ?? '0';
        }
        if (isset($body['itemKindBS'])) {
            $body['itemKindBS'] = $this->formatArray($body['itemKindBS']);
            foreach ($body['itemKindBS'] as $val) {
                $syPremium += $val['priceTaxTotal'];
            }
        }
        $riskInfo = $body['risk'] ?? [];
        $riskInfo = $this->formatArray($riskInfo);
        $jqRiskData = $syRiskData = [];
        foreach ($riskInfo as $val) {
            if ($val['riskCode'] == 'BZ') {
                $jqRiskData = $val;
            }
            if ($val['riskCode'] == 'BS') {
                $syRiskData = $val;
            }
        }
        //交强险
        $premiumInquiryPrinter->inquiryNo = '';//总询价单号
        $ciPremiumPrinter = new PremiumCIPrinter();
        $ciPremiumPrinter->ciPremium = round($jqPremium, 2);//交强险保费
        $ciPremiumPrinter->ciStartData = $jqRiskData['startDate'] ?? '';//交强险起保日期
        $ciPremiumPrinter->ciEndData = $jqRiskData['endDate'] ?? '';//交强险终保日期
        $premiumInquiryPrinter->ciPremiumPrinter = $ciPremiumPrinter;

        $carTaxPrinter = new PremiumTaxPrinter();
        $carTaxPrinter->carShipTax = $body['tax']['sumPayTax'] ?? 0;//车船税本年缴税合计
        $carTaxPrinter->thisYearTax = $body['tax']['sumPayTax'] ?? 0;//本年应缴税
        $premiumInquiryPrinter->carTaxPrinter = $carTaxPrinter;


        $biPremiumPrinter = new PremiumBIPrinter();
        $biPremiumPrinter->biPremium = round($syPremium, 2);//商业险保费
        $biPremiumPrinter->biStartData = $syRiskData['startDate'] ?? '';//商业险起保日期
        $biPremiumPrinter->biEndData = $syRiskData['endDate'] ?? '';//商业险终保日期
        $premiumInquiryPrinter->biPremiumPrinter = $biPremiumPrinter;

        //交商系数
        $factorPrinter = new PremiumFactorPrinter();
        $jqFactor = $this->formatArray($body['ncdBZ'] ?? []);
        $syFactor = $this->formatArray($body['ncdBS'] ?? []);
        if (!empty($syFactor)) foreach ($syFactor as $key => $val) {
            $factorPrinter->ComFactorAppend($val['factorCode'] ?? '', 'factorCode' . $key, round($val['adjustValue'] / 100, 2) ?? '');
            if (strpos($val['factorCode'], '无赔款优待系数') !== false) {
                $premiumInquiryPrinter->ncdFactor = round($val['adjustValue'] / 100, 2);
            }
        }
        if (!empty($jqFactor)) foreach ($jqFactor as $key => $val) {
            $factorPrinter->ComFactorAppend($val['factorCode'] ?? '', 'factorCode' . $key, round($val['adjustValue'] / 100, 2) ?? '');
        }
        if (isset($body['extend'])) {
            $factorPrinter->ComFactorAppend('折扣上限', 'discountUp', $body['extend']['discountUp'] ?? '');
            $factorPrinter->ComFactorAppend('折扣下限', 'discountDown', $body['extend']['discountDown'] ?? '');
            $str = '';
            if (($body['extend']['xzxId'] ?? '') == '0') {
                $str = '新';
            } elseif (($body['extend']['xzxId'] ?? '') == '1') {
                $str = '续';
            } elseif (($body['extend']['xzxId'] ?? '') == '2') {
                $str = '转';
            }
            $factorPrinter->ComFactorAppend('交强险忠诚度', 'CIRenewalType', $str);
            $factorPrinter->ComFactorAppend('商业险忠诚度', 'BIRenewalType', $str);
        }
        //非车结果回填
        $nonCarItem = $body['fcOrderInfo'] ?? [];
        if(!empty($nonCarItem)){
            $nonCarInquiryPrinter = new NonCarInquiryPrinter();
            $single = new NonCarInquirySinglePrinter();
            $single->premium = $nonCarItem['price'] ?? '0';
            $single->planCode = $nonCarItem['projectCode'] ?? '';
            $single->productCode = $nonCarItem['productCode'] ?? '';
            $single->statusCode = 'success';
            $totalPremium = $single->premium * ($nonCarItem['quantity'] ?? 1);
            $nonCarInquiryPrinter->totalPremium = $totalPremium;
            $nonCarInquiryPrinter->noCarInquirySingleAppend($single);
            $premiumInquiryPrinter->nonCarInquiryPrinter = $nonCarInquiryPrinter;
        }
        $premiumInquiryPrinter->premiumFactorPrinter = $factorPrinter;
        $this->printer = $premiumInquiryPrinter;
        return $this;
    }


    /**
     * @param $errMeg
     * @return void
     */
    public function getRepeatData($errMeg)
    {

        if (preg_match('/交强险[\s\S]*终保日期 ([\d\s:-]+)/', $errMeg, $matches)) {
            if ($matches[1] ?? '') {
                $ciStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $this->printer->repeatInsuredFlg = true;
                $this->printer->repeatInsurePrinter['ciStartData'] = $ciStartData;
            }
        }

        if (preg_match('/平台校验[\s\S]*终保日期 ([\d\s:-]+)/', $errMeg, $matches)) {
            if ($matches[1] ?? '') {
                $biStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $this->printer->repeatInsuredFlg = true;
                $this->printer->repeatInsurePrinter['biStartData'] = $biStartData;
            }
        }
    }

    public function formatCoverage($isNewEnergy)
    {
        $body = $this->getBody()['body'] ?? '';
        $coverageList = $this->formatArray($body['itemKindBS'] ?? []);
        foreach ($coverageList as $row) {
            $coverage = new PremiumCoveragePrinter();

            $coverage->coverageCode = array_search($row['kindCode'], TPICEnums::$coverageCode);
            if($isNewEnergy){
                $coverage->coverageCode = 'C1' . substr($coverage->coverageCode, '2', 4);
            }
            $coverage->coverageName = $row['kindName'];
            $coverage->amount = $row['sumInsured'] ?? 0;
            if(in_array($coverage->coverageCode,['C05001','C15001'])){
                $coverage->amount = round($coverage->amount * ($body['vehicle']['seatCount'] - 1),2);
            }
            $coverage->premium = $row['priceTaxTotal'] ?? 0;
            $coverage->basePremium = $row['benchmarkPremium'] ?? 0;//基础保额
            $coverage->discount = round($row['discount'] / 100, 2) ?? 0;//折扣
            $coverage->quantity = $row['quantity'] ?? '';
            $coverage->serviceTimes = $row['serviceTimes'] ?? 0;//服务次数
            $this->printer->coverageListAppend($coverage);
        }
    }
}
